package com.chookss.tools.old;


import android.os.Build;

import androidx.annotation.RequiresApi;

import com.johnrambo.ktea.net.http.RequestData;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.johnrambo.ktea.common.ToolsKt.logger;

/**
 * 签名的工具类
 */
public class SignUtils {
//    private static final Logger logger = LoggerFactory.getLogger(Constant.LOGGER);

    /**
     * 生成签名前缀 签名需要放到参数最后一个
     *
     * @param params      参数集合，
     * @param accessToken 登录token
     * @param secretKey   分给调用者的唯一key  拼接到最后
     * @return 对加密结果转大写
     */
//    @RequiresApi(api = Build.VERSION_CODES.N)
    public static String getSignStr(Map<String, Object> params, String accessToken, String secretKey) {
        List<String> list = new ArrayList<>();
        list.add("accessToken=" + accessToken);
        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
//            params.keySet().forEach(key -> {
                //非签名参数进行排序加密
                if (!key.equals("sign")) {
                    list.add(key + "=" + params.get(key));
                }
            }
        }
        Collections.sort(list);
        StringBuilder sb = new StringBuilder();
        for (String str : list) {
            sb.append(str).append("&");
        }
        sb.append("secretKey=" + secretKey);
        return getSha1(sb.toString()).toUpperCase();
    }

    public static String getSha1(String str) {
        MessageDigest md = null;
        String tmpStr = null;

        try {
            md = MessageDigest.getInstance("SHA-1");
            // 将三个参数字符串拼接成一个字符串进行sha1加密
            byte[] digest = md.digest(str.getBytes());
            tmpStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            //logger.error("签名加密异常：", e);
            logger("签名加密异常：");
        }
        return tmpStr;
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param byteArray
     * @return
     */
    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    /**
     * 将字节转换为十六进制字符串
     *
     * @param mByte
     * @return
     */
    private static String byteToHexStr(byte mByte) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];

        String s = new String(tempArr);
        return s;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public static void main(String[] args) {
        String timespan = "20201207161305";
        String notec = "20201207161305";
        String secretKey = "KMER_APP_API_SIGN";
        Map<String, Object> params = new HashMap<>();
        params.put("username", "admin");
        params.put("password", "admin");
        params.put("device", "admin");
        params.put("timestamp", timespan);
        params.put("nonce", notec);
        params.put("sign", "admin");
        String sign = getSignStr(params, "login", secretKey);
        System.out.println(sign);
    }

    public static String getTimeStamp() {
        long timecurrentTimeMillis = System.currentTimeMillis();
        SimpleDateFormat sdfTwo = new SimpleDateFormat("yyyyMMddHHmmss");
        String timeStamp = sdfTwo.format(timecurrentTimeMillis);
        //System.out.println(time11);
        return timeStamp;
    }

   /* val timeStamp = SignUtils.getTimeStamp() //20201208125238
    val secretKey = "KMER_APP_API_SIGN"
    val params: MutableMap<String, Any> = HashMap()
    params["username"] = username
    params["password"] = password
    params["device"] = "admin"
    params["timestamp"] = timeStamp
    params["nonce"] = timeStamp
    params["sign"] = "admin"
    val sign = SignUtils.getSignStr(params, "login", secretKey)
    logger("sign:$sign")*/

//    @RequiresApi(api = Build.VERSION_CODES.N)
    public static String makeSignStr(Map<String, Object> params, String timeStamp, String nonce, Boolean isLogin) {
        String secretKey = "KMER_APP_API_SIGN";

        String makeSign = "";
        params.put("timestamp", timeStamp);
        params.put("nonce", nonce);
        //如果是登录接口
        if (isLogin) {
            makeSign = getSignStr(params, "login", secretKey);
        } else {
            makeSign = getSignStr(params, RequestData.INSTANCE.getToken(), secretKey);
        }
        return makeSign;
    }
    //生成随机字符串
    public static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(20);
            sb.append(str.charAt(number));
        }
//        UUID.randomUUID();
        return sb.toString();
    }
}
